package top.go2do.homeGoods.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.go2do.common.httpResponseResult.ApiResponse;

import java.util.Locale;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/6/18 11:21
 */
@Order(1)
@RestControllerAdvice
@Slf4j
public class GoodsExceptionHandler {

    @Autowired
    private MessageSource messageSource;


    /**
     * 已知的业务异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(GoodsException.class)
    public ApiResponse<?> handleAuthException(GoodsException ex) {
        String msg = resolveMessage(ex.getMsgKey(), ex.getArgs(), LocaleContextHolder.getLocale());
        int code = ex.getCode();
        ApiResponse apiResponse = ApiResponse.error(code, msg);
        return apiResponse;
    }

    private String resolveMessage(String messageKey, @Nullable Object[] args, Locale locale) {
        try {
            // 通过 MessageSource 解析消息
            return messageSource.getMessage(messageKey, args, locale);
        } catch (NoSuchMessageException e) {
            log.warn("i18n message not found key:{}, lang:{}", messageKey, locale.toLanguageTag());
            return messageKey;
        }
    }
}
